package com.processor;

import com.annotation.CreateFile;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;

import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import java.util.Set;

@SupportedSourceVersion(SourceVersion.RELEASE_8)
@SupportedAnnotationTypes({"com.annotation.CreateFile"})
@AutoService(Processor.class)
@SupportedOptions("debug")
public class CreateSourceProcessor extends AbstractProcessor {
    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        Set<? extends Element> set = roundEnv.getElementsAnnotatedWith(CreateFile.class);
        for(Element element : set){
            CreateFile createFile = element.getAnnotation(CreateFile.class);
            if(element.getKind() == ElementKind.CLASS){
                MethodSpec main = MethodSpec.methodBuilder("main")
                        .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                        .returns(void.class)
                        .addParameter(String[].class, "args")
                        .addStatement("$T.out.println($S)", System.class, "HelloWord!")
                        .build();

                TypeSpec clazz = TypeSpec.classBuilder(createFile.fileName())
                        .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                        .addMethod(main)
                        .build();

                JavaFile javaFile = JavaFile.builder("com.javapoet", clazz).build();
                try{
                    javaFile.writeTo(this.processingEnv.getFiler());
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return false;
    }
}
